<template>
  <div class="body">
    <div class="body_main">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <a @click.stop="goBack">
            <el-button
              icon="el-icon-arrow-left"
              size="mini"
              circle
              style="margin-right: 12px"
            ></el-button>
            数据目录管理
          </a>
        </el-breadcrumb-item>
        <el-breadcrumb-item
          style="height: 28px; line-height: 28px"
          >数据配置
        </el-breadcrumb-item>
      </el-breadcrumb>
      <div class="line"></div>
      <el-select
        placeholder="请选择唯一字段"
        v-model="defaultProperty"
        :disabled="!!featureData.attributeWord"
        class="select-pro"
      >
        <el-option
          v-for="(item, index) in propertyList"
          :key="index"
          :label="item"
          :value="item"
        ></el-option>
      </el-select>
      <el-button
        style="width: 80px; padding: 10px 0px"
        v-show="!featureData.attributeWord"
        @click="selectProperty"
      >
        确认选择
      </el-button>
      <span class="select-right">
        <el-select
          placeholder="选择字段"
          class="select-pro"
          v-model="field"
          style="width: 120px"
          clearable
          @change="listByProperty"
        >
          <el-option
            v-for="(item, index) in fieldList"
            :key="index"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
        <el-input
          v-model="fieldValue"
          property="请输入关键字"
          clearable
          style="width: 200px; margin: 10px 10px 0px -12px"
          @input="listByProperty"
          @change="listByProperty"
        >
          <el-button slot="append" @click="listByProperty"
            >搜索</el-button
          >
        </el-input>
        <el-select
          placeholder="配置状态"
          class="select-pro"
          v-model="defaultStatus"
          @change="changeConfigStatus"
          style="width: 150px"
          clearable
        >
          <el-option
            v-for="(item, index) in configStatusList"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <div class="select-timeRange">
          <el-date-picker
            v-model="defaultTimeRange"
            type="datetimerange"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="changeTimeRange"
          >
          </el-date-picker>
        </div>
      </span>
      <div class="line"></div>
      <div class="config_info_content">
        <el-table
          :data="dataConfigList"
          v-loading="isLoading"
          :header-cell-style="{
            background: '#F2F6FB ',
            color: ' #6B767D'
          }"
          ref="table"
          :row-class-name="tableRowClassName"
          row-key="pkid"
        >
          <el-table-column
            label="序号"
            align="center"
            show-overflow-tooltip
            width="80"
          >
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>

          <el-table-column
            show-overflow-tooltip
            v-for="(item, index) in propertyList"
            :key="index"
            :label="item"
            :prop="item"
          />
          <el-table-column
            prop="status"
            label="配置状态"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span
                v-if="scope.row.status == 0"
                style="color: red"
                >未配置</span
              >
              <span
                v-if="scope.row.status == 1"
                style="color: #0098ff"
                >已配置</span
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="updateTime"
            label="更新时间"
            show-overflow-tooltip
          />
          <el-table-column
            label="操作"
            v-if="featureData.attributeWord"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                :disabled="!featureData.attributeWord"
                @click="configData(scope.row)"
                style="color: #00baff; font-weight: 400"
                >数据配置
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div
        style="float: right; margin-top: 15px"
        v-if="total"
      >
        <el-pagination
          background
          layout="prev,pager,next,jumper"
          :page-size="parameter.pageSize"
          @current-change="pageChange"
          :current-page="parameter.pageIndex"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import {
  updateDataService,
  queryConfigList
} from '@/api/multiple-dataservice'
import dayjs from 'dayjs'

export default {
  name: 'catalogueAllocation',
  data() {
    return {
      propertyList: [],
      fieldList: [],
      field: [],
      fieldValue: '',
      featureData: '',
      dataConfigList: [],
      defaultProperty: '',
      defaultStatus: '',
      configStatusList: [
        {
          label: '已配置',
          value: '2'
        },
        {
          label: '未配置',
          value: '1'
        }
      ],
      defaultTimeRange: [],
      total: '',
      parameter: {
        pageSize: 10,
        pageIndex: 1
      },
      isLoading: true,
      attributeValueList: null
      // updateTime:'',
    }
  },
  mounted() {
    this.featureData = JSON.parse(
      localStorage.getItem('dataServiceInfo')
    )
    this.defaultProperty = this.featureData.attributeWord
    this.getProperty()
    localStorage.removeItem('configAppendixShow')
    // let serviceUrl = this.featureData.serviceDataUrl + '/features.json?toIndex=-1'
    // let featureUrlList = []
    // axios.get(serviceUrl).then(res => {
    //   res.data.childUriList.forEach(val => {
    //     let url = val + '.json'
    //     featureUrlList.push(url)
    //   })
    //   this.total = featureUrlList.length
    //   this.featureUrlList = featureUrlList
    //   let thisPageData = featureUrlList.slice(0, 15)
    //   let requestList = []
    //   thisPageData.forEach(url => {
    //     requestList.push(axios.get(url))
    //   })
    //   Promise.all(requestList).then(item => {
    //     let fieldNames = item[0].data.fieldNames
    //     let propertyList = []
    //     fieldNames.forEach(fieldName => {
    //       propertyList.push({
    //         label: fieldName,
    //         value: fieldName
    //       })
    //     })
    //     this.propertyList = propertyList
    //     this.defaultProperty = this.propertyList[0].value
    //     console.log(fieldNames)
    //     let dataList = []
    //     item.forEach(i => {
    //       let fieldValues = i.data.fieldValues
    //       let va = {}
    //       fieldValues.forEach((value, idx) => {
    //         va[fieldNames[idx]] = value
    //       })
    //       va.updateTime = '2022-02-23 12:00:00'va.updateTime = '2022-02-23 12:00:00'
    //       dataList.push(va)
    //     })
    //     this.isLoading = false
    //     this.dataConfigList = dataList
    //   })
    // })
  },
  methods: {
    // 获取字段列表
    getFieldList() {
      axios
        .get(
          `${this.featureData.serviceDataUrl}/fields.json`
        )
        .then((res) => {
          // if (res.status === 200 && res.data) {
          if (res.data) {
            this.propertyList = res.data.fieldNames
            this.fieldList = this.propertyList.filter(
              (e) => e.toLowerCase().indexOf('sm') !== 0
            )
            // console.log(this.fieldList)
            this.getTableList()
          }
        })
    },
    timeInDateBetwen(time1, time2, theTime) {
      const dateBegin = new Date(time1) // 将-转化为/，使用new Date
      const dateEnd = new Date(time2) // 将-转化为/，使用new Date
      const dateNow = new Date(theTime) // 获取当前时间
      const beginDiff =
        dateNow.getTime() - dateBegin.getTime() // 时间差的毫秒数
      const beginDayDiff = Math.floor(
        beginDiff / (24 * 3600 * 1000)
      ) // 计算出相差天数

      const endDiff = dateEnd.getTime() - dateNow.getTime() // 时间差的毫秒数
      const endDayDiff = Math.floor(
        endDiff / (24 * 3600 * 1000)
      ) // 计算出相差天数
      if (endDayDiff < 0) {
        // 已过期
        return false
      }
      if (beginDayDiff < 0) {
        // 没到开始时间
        return false
      }
      return true
    },
    // 获取数据列表
    getTableList() {
      const dataService = this.featureData.serviceDataUrl
      const dataServiceUrl =
        dataService.substring(
          0,
          dataService.lastIndexOf('/datasources/')
        ) +
        `/featureResults.json?returnContent=true&fromIndex=${
          (this.parameter.pageIndex - 1) * 10
        }&toIndex=${this.parameter.pageIndex * 10 - 1}`
      // console.log('请求地址', dataServiceUrl)
      const dataSourceAndDataSet = dataService
        .substring(
          dataService.lastIndexOf('/datasources/') +
            '/datasources/'.length
        )
        .split('/datasets/')
        .map((item) => decodeURI(item))
      // 搜索的sql
      const attributeFilter = this.field
        ? `${this.field} like '%${this.fieldValue}%'`
        : ''
      // 时间的sql
      let timeFilter
      if (
        this.defaultTimeRange &&
        this.defaultTimeRange.length
      ) {
        for (const key in this.attributeValueList) {
          if (
            this.timeInDateBetwen(
              this.defaultTimeRange[0],
              this.defaultTimeRange[1],
              dayjs(this.attributeValueList[key]).format(
                'YYYY-MM-DD HH:mm:ss'
              )
            ) &&
            this.defaultStatus !== '1'
          ) {
            if (!timeFilter) {
              timeFilter = `${this.featureData.attributeWord} = '${key}'`
            } else {
              timeFilter +=
                ' or ' +
                `${this.featureData.attributeWord} = '${key}'`
            }
          }
        }
      }
      // 状态的sql
      let statusFilter
      if (
        this.defaultStatus === '2' &&
        (!this.defaultTimeRange ||
          !this.defaultTimeRange.length)
      ) {
        const keys = Object.keys(this.attributeValueList)
        statusFilter = `${this.featureData.attributeWord} = '${keys[0]}'`
        const length = keys.length
        for (let i = 1; i < length; i++) {
          statusFilter +=
            ' or ' +
            `${this.featureData.attributeWord} = '${keys[i]}'`
        }
      }
      if (this.defaultStatus === '1') {
        const keys = Object.keys(this.attributeValueList)
        statusFilter = `${this.featureData.attributeWord} <> '${keys[0]}'`

        const length = keys.length
        for (let i = 1; i < length; i++) {
          statusFilter +=
            ' AND ' +
            `${this.featureData.attributeWord} <> '${keys[i]}'`
        }
      }
      // 将sql组合
      let filter = ''
      if (attributeFilter) {
        filter = attributeFilter
      }
      if (filter) {
        if (statusFilter) {
          filter += ' AND ' + statusFilter
        }
      } else {
        filter = statusFilter
      }
      if (filter) {
        if (timeFilter) {
          filter += ' AND ' + timeFilter
        }
      } else {
        filter = timeFilter
      }
      // console.log(filter)
      const sqlParameter = {
        datasetNames: [`${dataSourceAndDataSet.join(':')}`],
        getFeatureMode: 'SQL',
        queryParameter: {
          fields: this.propertyList,
          attributeFilter: filter
          // groupBy: `${val.label}`
        },
        hasGeometry: false
      }
      const queryData = JSON.stringify(sqlParameter)
      axios.post(dataServiceUrl, queryData).then((res) => {
        // console.log('res.data', res.data)
        this.total = res.data.featureCount
        this.dataConfigList = []
        if (res.data.featureCount > 0) {
          const list = res.data.features
          // .slice(
          //   (this.parameter.pageIndex - 1) * this.parameter.pageSize,
          //   this.parameter.pageIndex * this.parameter.pageSize
          // )
          // const fieldNames = list[0].fieldNames
          let dataList = []
          list.forEach((i) => {
            const fieldValues = i.fieldValues
            const va = {}
            fieldValues.forEach((value, idx) => {
              va[this.propertyList[idx]] = value
              va.status = '0'
              va.updateTime = ''
              // va.updateTime = '2022-02-23 12:00:00'
            })
            dataList.push(va)
          })
          dataList = dataList.map((item) => {
            const value =
              item[this.featureData.attributeWord]
            if (
              Object.keys(this.attributeValueList).indexOf(
                value
              ) !== -1
            ) {
              item.status = '1'
              item.updateTime = this.attributeValueList[
                value
              ]
                ? dayjs(
                    this.attributeValueList[value]
                  ).format('YYYY-MM-DD HH:mm:ss')
                : ''
            }
            return item
            // if()
          })
          // if (this.defaultStatus == 1) {
          //   dataList = dataList.filter((e) => {
          //     return e.status == '0'
          //   })
          // } else if (this.defaultStatus == 2) {
          //   dataList = dataList.filter((e) => {
          //     return e.status == '1'
          //   })
          // }
          // if (
          //   this.defaultTimeRange &&
          //   this.defaultTimeRange.length
          // ) {
          //   dataList = dataList.filter((e) => {
          //     return (
          //       e.updateTime &&
          //       Date.parse(
          //         e.updateTime.replace(/-/g, '/')
          //       ) >=
          //       Date.parse(
          //         this.defaultTimeRange[0].replace(
          //           /-/g,
          //           '/'
          //         )
          //       ) &&
          //       Date.parse(
          //         e.updateTime.replace(/-/g, '/')
          //       ) <=
          //       Date.parse(
          //         this.defaultTimeRange[1].replace(
          //           /-/g,
          //           '/'
          //         )
          //       )
          //     )
          //   })
          // }
          this.total = res.data.totalCount
          this.isLoading = false
          this.dataConfigList = dataList
        }
      })
    },
    // getNextPageData(thisPageData) {
    //   let requestList = []
    //   thisPageData.forEach(url => {
    //     requestList.push(axios.get(url))
    //   })
    //   Promise.all(requestList).then(item => {
    //     let fieldNames = item[0].data.fieldNames
    //     let propertyList = []
    //     fieldNames.forEach(fieldName => {
    //       propertyList.push({
    //         label: fieldName,
    //         value: fieldName
    //       })
    //     })
    //     let dataList = []
    //     item.forEach(i => {
    //       let fieldValues = i.data.fieldValues
    //       let va = {}
    //       fieldValues.forEach((value, idx) => {
    //         va[fieldNames[idx]] = value
    //       })
    //       va.updateTime = '2022-02-23 12:00:00'
    //       dataList.push(va)
    //     })
    //     this.isLoading = false
    //     this.dataConfigList = dataList
    //   })
    // },
    listByProperty() {
      // if(!this.field){
      //   this.$message.warning('请选择筛选查询字段')
      //   return
      // }
      // this.$set(this.parameter, 'pageIndex', 1)

      this.parameter.pageIndex = 1
      this.getTableList()
    },
    selectProperty() {
      if (!this.defaultProperty) {
        this.$message('请选择唯一字段后再进行确认')
        return
      }
      const data = [this.featureData]
      data[0].attributeWord = this.defaultProperty
      updateDataService(data).then((res) => {
        if (res.success) {
          const tempData = JSON.parse(
            localStorage.getItem('dataServiceInfo')
          )
          tempData.attributeWord = this.defaultProperty
          localStorage.setItem(
            'dataServiceInfo',
            JSON.stringify(this.featureData)
          )
          this.$message.success(res.data)
        }
      })
    },
    getProperty() {
      // let data={
      //   serviceDataId:this.featureData.serviceDataId
      // }
      queryConfigList(this.featureData.pkid).then((res) => {
        if (res.success) {
          this.attributeValueList = res.data
          this.getFieldList()
        }
      })
    },
    goBack() {
      this.$router.back()
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'light'
      } else {
        return ''
      }
    },
    configData(row) {
      // console.log(row)
      // console.log(this.featureData[row])
      this.featureData.attributeValue =
        row[this.featureData.attributeWord]
      // console.log(this.featureData)
      localStorage.setItem(
        'dataServiceWithValue',
        JSON.stringify(this.featureData)
      )
      this.$router.push({
        path: '/mochaITOM/catalogueManagement/catalogueDataAllocation'
        // query: { data: JSON.stringify(this.featureData) }
      })
    },
    pageChange(page) {
      this.parameter.pageIndex = page
      this.getTableList()
      // let thisPageData = this.featureUrlList.slice((page - 1) * 15, page * 15)
      // this.isLoading = true
      // this.getNextPageData(thisPageData)
    },
    changeConfigStatus() {
      this.parameter.pageIndex = 1
      this.getTableList()
    },
    changeTimeRange() {
      this.parameter.pageIndex = 1
      this.getTableList()
    }
  }
}
</script>

<style lang="scss" scoped>
.body {
  width: calc(100% - 26px);
  height: calc(100% - 20px);
  padding: 18px 15px 15px 16px;

  &_main {
    width: calc(100% - 26px);
    height: calc(100% - 20px);
    background: white;
    padding: 15px 30px;
    border-radius: 2px;

    .line {
      margin-top: 12px;
      width: 1600px;
      height: 1px;
      background: #f1f1f1;
      //margin-bottom: 23px;
    }

    ::v-deep.light {
      background: #f9fcff;
      border: 1px solid #f2f6fb !important;
    }

    ::v-deep .el-table__row {
      .el-table__cell {
        padding: 10px 0 !important;
        color: #4c565c;

        .el-button {
          padding: 0 !important;
        }
      }
    }

    ::v-deep {
      .el-pagination {
        &__jump {
          display: inline-flex !important;
          align-items: center;

          .el-input {
            &__inner {
              height: 28px !important;
            }
          }
        }
      }
    }
  }
}

.config_info_content {
  width: 100%;
  height: calc(100% - 146px);
}

::v-deep {
  .el-table {
    height: 100%;
    overflow: scroll;

    &::before {
      height: 0;
    }
  }

  .el-table__body {
    &-wrapper {
      &::-webkit-scrollbar-track {
        background-color: #f2f6fb;
      }

      //::-webkit-scrollbar {
      //  height: 6px!important;
      //  width: 6px!important;
      //}

      &::-webkit-scrollbar-corner {
        background-color: #f2f6fb;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 5px;
        //height: 6px;
        //width: 6px;
        background-color: rgba(128, 128, 128, 0.27);

        &:hover {
          background-color: rgba(128, 128, 128, 0.76);
        }
      }
    }
  }
}

.select-pro {
  margin: 10px 10px 0px 0px;
}

.select-right {
  display: flex;
  float: right;
  right: 0;
}

::v-deep {
  .el-select {
    .el-input__suffix {
      top: 4px !important;
    }

    .is-focus {
      .el-input__suffix {
        top: -3px !important;
      }
    }
  }

  .el-input__inner {
    height: 34px !important;
    background-color: #f6f9fc !important;
  }

  .el-range-separator,
  .el-date-editor .el-range__icon,
  .el-date-editor .el-range__close-icon {
    margin-top: -6px !important;
  }
}

.select-timeRange {
  margin-top: 10px;
}
</style>
